﻿using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using FurionApiDemo.Core.Entity;
using FurionApiDemo.Core.Implementt.User.Dtos;
using FurionApiDemo.Core.Manager.User;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace FurionApiDemo.Core.Implement
{
    /// <summary>
    /// 用户角色服务
    /// </summary>
    public class UserRoleService : IUserRoleService, ITransient
    {
        private readonly IRepository<SysUserRole> _sysUserRoleRep;  // 用户权限表仓储 
        private readonly IUserManager _userManager;

        private readonly IRoleService _sysRoleService;

        public UserRoleService(IRepository<SysUserRole> sysUserRoleRep,
            IRoleService sysRoleService,
            IUserManager userManager)
        {
            _sysUserRoleRep = sysUserRoleRep;
            _sysRoleService = sysRoleService;
            _userManager = userManager;
        }

        /// <summary>
        /// 获取用户的角色Id集合
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<List<long>> GetUserRoleIdList(long userId)
        {
            return await _sysUserRoleRep.DetachedEntities.Where(u => u.UserId == userId).Select(u => u.RoleId).ToListAsync();
        }

        /// <summary>
        /// 授权用户角色
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="RoleIds"></param>
        /// <returns></returns>
        public async Task GrantRole(long UserId, List<long> RoleIds)
        {
            var userRoles = await _sysUserRoleRep.Where(u => u.UserId == UserId).ToListAsync();
            userRoles.ForEach(u =>
            {
                u.DeleteNow();
            });

            RoleIds.ForEach(u =>
            {
                new SysUserRole
                {
                    UserId = UserId,
                    RoleId = u
                }.InsertNow();
            });
        }

        /// <summary>
        /// 根据角色Id删除对应的用户-角色表关联信息
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public async Task DeleteUserRoleListByRoleId(long roleId)
        {
            var userRoles = await _sysUserRoleRep.Where(u => u.RoleId == roleId).ToListAsync();
            userRoles.ForEach(u =>
            {
                u.DeleteNow();
            });
        }

        /// <summary>
        /// 根据用户Id删除对应的用户-角色表关联信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task DeleteUserRoleListByUserId(long userId)
        {
            var userRoles = await _sysUserRoleRep.Where(u => u.UserId == userId).ToListAsync();
            userRoles.ForEach(u =>
            {
                u.DeleteNow();
            });
        }
    }
}
